import csv
import sys
import traceback
from datetime import datetime

import mysql.connector
from PyQt5.QtChart import QChartView, QChart, QLineSeries, QValueAxis
from mysql.connector import Error
from PyQt5.QtWidgets import (
    QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QLabel,
    QPushButton, QTabWidget, QMessageBox, QDialog, QFormLayout, QLineEdit, QGroupBox, QComboBox, QDateEdit,
    QAbstractItemView, QTableWidget, QStyledItemDelegate, QHeaderView, QTableWidgetItem, QFileDialog,
)
from PyQt5.QtGui import QFont, QIcon, QPainter, QColor, QBrush
from PyQt5.QtCore import Qt, QDate

# 导入功能模块
from GUIdesign.easy_pass_tap import BankCardManager
from GUIdesign.easy_pass_tap import PasswordChangeDialog #修改密码
from GUIdesign.Customer_money_tap import CustomerOperationWindow  # 余额查询
from GUIdesign.Customer_moneyTs_tap import TransferWindow  # 转账
from GUIdesign.Customer_reportloss import ReportLossWindow  # 挂失/解挂
from GUIdesign.Customer_moneyTs_tap import TransactionManager  # 交易管理器
from GUIdesign.Customer_reportloss import CustomerManager  # 导入客户管理器


class DBUtils:
    """数据库工具类 - 完整修复版"""

    def __init__(self):
        self.connection = None
        self._connect()  # 初始化时立即尝试连接

    def _connect(self):
        """建立数据库连接 - 修复版"""
        try:
            # 如果已有连接且有效，则直接返回
            if self.connection and self.connection.is_connected():
                return True

            # 创建新连接
            self.connection = mysql.connector.connect(
                host='localhost',
                database='bank system',
                user='root',
                password='1234',
                autocommit=True,
                connect_timeout=5  # 添加连接超时
            )

            if self.connection.is_connected():
                print(f"成功连接到MySQL服务器 (版本 {self.connection.server_version})")
                return True
            return False

        except Error as e:
            print(f"数据库连接失败: {e}")
            traceback.print_exc()
            raise ConnectionError(f"无法连接数据库: {str(e)}")

    def is_connected(self):
        """检查连接状态"""
        try:
            return self.connection and self.connection.is_connected()
        except:
            return False

    def execute_query(self, query, params=None, fetch=True):
        """执行SQL查询 - 修复版"""
        cursor = None
        try:
            # 确保连接有效
            if not self.is_connected():
                print("连接已断开，尝试重新连接...")
                if not self._connect():
                    print("无法重新连接到数据库")
                    return None

            cursor = self.connection.cursor(dictionary=True)
            cursor.execute(query, params or ())

            if fetch:
                result = cursor.fetchall()
                return result if result else []
            else:
                self.connection.commit()
                return True

        except Error as e:
            print(f"查询执行失败: {e}")
            traceback.print_exc()
            if self.connection:
                self.connection.rollback()
            return None
        finally:
            if cursor:
                cursor.close()

    def disconnect(self):
        """安全关闭连接"""
        if self.is_connected():
            try:
                self.connection.close()
                print("数据库连接已关闭")
            except Error as e:
                print(f"关闭连接时出错: {e}")
        self.connection = None

class CustomerLoginDialog(QDialog):
    """客户登录对话框"""

    def __init__(self, parent=None):
        super().__init__(parent)
        self.card_info = None  # 存储登录成功的卡信息
        self.setup_ui()

    def setup_ui(self):
        """初始化登录界面（仅保留卡号密码输入）"""
        # 设置窗口大小和背景
        self.setFixedSize(800, 600)
        self.setStyleSheet("""
            QDialog {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 #1e5799, stop:1 #2989d8);
            }
            QLabel {
                color: white;
                font-size: 16px;
            }
            QLineEdit {
                padding: 8px;
                font-size: 14px;
                border-radius: 4px;
                border: 1px solid #ccc;
            }
            QPushButton {
                background-color: #3498db;
                color: white;
                font-size: 16px;
                font-weight: bold;
                padding: 10px 20px;
                border-radius: 5px;
                min-width: 120px;
                border: none;
            }
            QPushButton:hover {
                background-color: #2980b9;
            }
        """)

        layout = QVBoxLayout()
        layout.setContentsMargins(100, 50, 100, 50)
        layout.setSpacing(30)

        # 标题（保留）
        title_label = QLabel("欢迎使用银行管理系统")
        title_label.setAlignment(Qt.AlignCenter)
        title_label.setStyleSheet("font-size: 24px; font-weight: bold;")
        layout.addWidget(title_label)

        # 登录表单（仅保留卡号和密码输入）
        form_layout = QFormLayout()
        form_layout.setSpacing(15)
        form_layout.setLabelAlignment(Qt.AlignRight)

        # 卡号输入
        self.card_input = QLineEdit()
        self.card_input.setPlaceholderText("请输入16位银行卡号")
        self.card_input.setMaxLength(16)
        form_layout.addRow("卡号:", self.card_input)

        # 密码输入
        self.pwd_input = QLineEdit()
        self.pwd_input.setPlaceholderText("请输入6位密码")
        self.pwd_input.setMaxLength(6)
        self.pwd_input.setEchoMode(QLineEdit.Password)
        form_layout.addRow("密码:", self.pwd_input)

        # 登录按钮
        login_btn = QPushButton("登录")
        login_btn.clicked.connect(self.verify_credentials)
        form_layout.addRow("", login_btn)

        layout.addLayout(form_layout)
        self.setLayout(layout)

    def verify_credentials(self):
        """验证用户凭据"""
        card_id = self.card_input.text().strip()
        password = self.pwd_input.text().strip()

        # 输入验证
        if len(card_id) != 16 or not card_id.isdigit():
            QMessageBox.warning(self, "错误", "卡号必须为16位数字")
            return

        if len(password) != 6 or not password.isdigit():
            QMessageBox.warning(self, "错误", "密码必须为6位数字")
            return

        db = None
        try:
            db = DBUtils()

            # 检查连接是否成功
            if not db.is_connected():
                QMessageBox.critical(self, "数据库错误", "无法连接到数据库")
                return

            # 执行查询
            query = """
            SELECT cardID, customerID, balance, IsReportLoss 
            FROM cardInfo 
            WHERE cardID = %s AND pass = %s
            """
            result = db.execute_query(query, (card_id, password))

            if not result:
                QMessageBox.warning(self, "登录失败", "卡号或密码错误")
                return

            # 存储卡信息
            card_info = result[0]
            self.card_info = {
                'card_id': card_info['cardID'],
                'customer_id': card_info['customerID'],
                'balance': card_info['balance'],
                'status': card_info['IsReportLoss'] == '是'
            }

            # 检查卡片状态
            if self.card_info['status']:
                QMessageBox.warning(self, "登录失败", "该卡已挂失，无法登录，联系管理员解挂")
                return

            self.accept()  # 登录成功

        except ConnectionError as e:
            QMessageBox.critical(self, "数据库错误", f"无法连接数据库: {str(e)}")
        except Exception as e:
            QMessageBox.critical(self, "错误", f"登录时发生错误: {str(e)}")
            traceback.print_exc()
        finally:
            if db:
                db.disconnect()

class CustomerDashboard(QMainWindow):
    """客户主界面 - 整合余额查询、转账和挂失功能"""

    def __init__(self, card_info=None,welcome_screen=None):
        super().__init__()
        self.card_info = card_info
        self.bank_manager = BankCardManager()  # 添加银行卡片管理器实例
        self.welcome_screen = welcome_screen  # 保存WelcomeScreen引用
        self.chart_view = None  # 添加图表视图引用


        if card_info:
            self.setWindowTitle(f"银行系统 - 客户面板 ({card_info['card_id']})")
        else:
            self.setWindowTitle("银行系统 - 客户面板")

        self.setMinimumSize(1100,1200)

        try:
            # 初始化数据库工具和管理器
            self.db = DBUtils()
            if not self.db.is_connected():
                raise ConnectionError("无法连接到数据库")

            # 初始化管理器
            self.transaction_manager = TransactionManager(self.db)
            self.customer_manager = CustomerManager(self.db)

            # 设置UI
            self.setup_ui()

        except ConnectionError as e:
            QMessageBox.critical(self, "数据库错误", str(e))
            self.close()
        except Exception as e:
            QMessageBox.critical(self, "初始化错误", f"初始化失败: {str(e)}")
            traceback.print_exc()
            self.close()

    def setup_ui(self):
        """设置界面UI"""
        self.setStyleSheet("""
            QMainWindow {
                background-color: #f0f0f0;
            }
            QTabWidget::pane {
                border: 1px solid #d4d4d4;
                background: #f9f9f9;
            }
            QTabBar::tab {
                background: #e0e0e0;
                border: 1px solid #d4d4d4;
                border-bottom-color: #d4d4d4;
                padding: 8px 15px;
                margin-right: 2px;
                border-top-left-radius: 4px;
                border-top-right-radius: 4px;
                color: #555;
            }
            QTabBar::tab:selected, QTabBar::tab:hover {
                background: #f9f9f9;
                color: #333;
            }
        """)

        # 创建主布局
        self.main_widget = QWidget()
        self.main_layout = QVBoxLayout(self.main_widget)
        self.main_layout.setContentsMargins(10, 10, 10, 10)
        self.main_layout.setSpacing(15)

        # 添加标题
        title_label = QLabel("银行系统 - 客户面板")
        title_label.setStyleSheet("""
            QLabel {
                font-size: 18px;
                font-weight: bold;
                color: #2c3e50;
                padding: 10px 0;
            }
        """)
        title_label.setAlignment(Qt.AlignCenter)
        self.main_layout.addWidget(title_label)



        # 账户信息栏
        account_info = QGroupBox("账户信息")
        account_layout = QHBoxLayout()



        # 左侧账户详情
        account_details = QWidget()
        detail_layout = QFormLayout()

        self.card_label = QLabel(self.card_info['card_id'])
        self.card_label.setStyleSheet("font-weight: bold;")

        self.customer_label = QLabel(str(self.card_info['customer_id']))
        self.customer_label.setStyleSheet("font-weight: bold;")

        self.balance_label = QLabel(f"¥{self.card_info['balance']:.2f}")
        self.balance_label.setStyleSheet("font-size: 18px; color: #27ae60; font-weight: bold;")

        status_text = "已挂失" if self.card_info['status'] else "正常"
        status_color = "#e74c3c" if self.card_info['status'] else "#27ae60"
        self.status_label = QLabel(status_text)
        self.status_label.setStyleSheet(f"font-size: 18px; color: {status_color}; font-weight: bold;")

        detail_layout.addRow("卡号:", self.card_label)
        detail_layout.addRow("客户ID:", self.customer_label)
        detail_layout.addRow("当前余额:", self.balance_label)
        detail_layout.addRow("状态:", self.status_label)
        account_details.setLayout(detail_layout)

        # 右侧快捷操作
        quick_actions = QWidget()
        action_layout = QVBoxLayout()

        # 在账户信息区域添加查询按钮
        query_btn = QPushButton("交易记录查询")
        query_btn.setStyleSheet("""
                    QPushButton {
                        background-color: #9b59b6;
                        color: white;
                        padding: 8px;
                        border-radius: 5px;
                        font-weight: bold;
                    }
                    QPushButton:hover {
                        background-color: #8e44ad;
                    }
                """)
        action_layout.addWidget(query_btn)  # 添加到现有按钮组
        query_btn.clicked.connect(self.show_transaction_query)

        refresh_btn = QPushButton("刷新余额")
        refresh_btn.setStyleSheet("""
            QPushButton {
                background-color: #3498db;
                color: white;
                padding: 8px;
                border-radius: 5px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #2980b9;
            }
        """)
        refresh_btn.clicked.connect(self.refresh_balance)

        logout_btn = QPushButton("退出登录")
        logout_btn.setStyleSheet("""
            QPushButton {
                background-color: #e74c3c;
                color: white;
                padding: 8px;
                border-radius: 5px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #c0392b;
            }
        """)
        logout_btn.clicked.connect(self.logout)

        action_layout.addWidget(refresh_btn)
        action_layout.addWidget(logout_btn)
        action_layout.addStretch()
        quick_actions.setLayout(action_layout)

        account_layout.addWidget(account_details)
        account_layout.addWidget(quick_actions)
        account_info.setLayout(account_layout)
        self.main_layout.addWidget(account_info)

        # 创建标签页
        self.tab_widget = QTabWidget()

        # 余额查询界面
        self.balance_tab = CustomerOperationWindow(
            card_id=self.card_info['card_id'],
            customer_id=self.card_info['customer_id'],
            balance=self.card_info['balance'],
            transaction_manager=self.transaction_manager
        )
        self.tab_widget.addTab(self.balance_tab, "余额查询")

        # 转账界面
        self.transfer_tab = TransferWindow(
            card_id=self.card_info['card_id'],
            customer_id=self.card_info['customer_id'],
            balance=self.card_info['balance']
        )
        self.tab_widget.addTab(self.transfer_tab, "转账")

        # 挂失/解挂界面 - 关键修复：传递 DBUtils 实例而不是 CustomerManager
        self.report_loss_tab = ReportLossWindow(
            card_id=self.card_info['card_id'],
            customer_id=self.card_info['customer_id'],
            balance=self.card_info['balance'],
            db_utils=self.db  # 传递 DBUtils 实例
        )
        self.tab_widget.addTab(self.report_loss_tab, "挂失/解挂")

        # === 添加月度趋势标签页 ===
        self.trend_tab = MonthlyTrendWindow(
            card_id=self.card_info['card_id'],
            transaction_manager=self.transaction_manager
        )
        self.tab_widget.addTab(self.trend_tab, "月度收支趋势")

        self.main_layout.addWidget(self.tab_widget)

        # 添加状态栏
        self.status_bar = self.statusBar()
        self.status_bar.showMessage("就绪")

        # 添加退出按钮
        exit_btn = QPushButton("退出系统")
        exit_btn.setStyleSheet("""
            QPushButton {
                background-color: #e74c3c;
                color: white;
                padding: 8px 16px;
                border-radius: 4px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #c0392b;
            }
        """)
        exit_btn.setMinimumHeight(40)
        exit_btn.clicked.connect(self.close)
        self.main_layout.addWidget(exit_btn)
        self.setCentralWidget(self.main_widget)

        # 应用图标
        self.setWindowIcon(QIcon(":/icons/customer.png"))  # 假设有合适的图标资源

        # 在账户信息栏添加修改密码按钮
        change_pwd_btn = QPushButton("修改密码")
        change_pwd_btn.setStyleSheet("""
                    QPushButton {
                        background-color: #f39c12;
                        color: white;
                        padding: 8px;
                        border-radius: 5px;
                        font-weight: bold;
                    }
                    QPushButton:hover {
                        background-color: #e67e22;
                    }
                """)
        change_pwd_btn.clicked.connect(self.show_password_change_dialog)

        # 添加到action_layout中
        action_layout.addWidget(refresh_btn)
        action_layout.addWidget(change_pwd_btn)  # 添加修改密码按钮
        action_layout.addWidget(logout_btn)

    def show_password_change_dialog(self):
        """显示密码修改对话框 - 修复版"""
        dialog = PasswordChangeDialog(
            card_id=self.card_info['card_id'],
            bank_manager=self.bank_manager  # 传递 BankCardManager 实例
        )
        dialog.exec_()

    def refresh_balance(self):
        """刷新账户余额"""
        try:
            query = "SELECT balance FROM cardInfo WHERE cardID = %s"
            result = self.db.execute_query(query, (self.card_info['card_id'],))

            if result and len(result) > 0:
                new_balance = result[0]['balance']
                self.card_info['balance'] = new_balance
                self.balance_label.setText(f"¥{new_balance:.2f}")

                # 更新标签页中的余额显示
                self.balance_tab.balance = new_balance
                if hasattr(self.balance_tab, 'balance_label'):
                    self.balance_tab.balance_label.setText(f"¥{new_balance:.2f}")

                self.status_bar.showMessage("余额已更新", 3000)
        except Exception as e:
            QMessageBox.warning(self, "错误", f"刷新余额失败: {str(e)}")
            self.status_bar.showMessage("刷新余额失败", 3000)

    def logout(self):
        """退出登录 - 修复版"""
        # 关闭数据库连接
        if self.db:
            try:
                self.db.disconnect()
                self.db = None
            except:
                pass

        # 关闭当前窗口
        self.close()

        # 如果存在 WelcomeScreen 引用，显示它
        if self.welcome_screen:
            self.welcome_screen.show()

    def show_transaction_query(self):
        """显示交易记录查询窗口"""
        # 创建交易记录查询管理器
        from Customer.transaction_query import integrate_transaction_query
        self.query_manager = integrate_transaction_query(
            self.card_info['card_id'], self.db
        )
        self.query_manager.show_query_window(self)

class MonthlyTrendWindow(QWidget):
    """月度收支趋势图窗口 - 使用数据库真实数据"""

    def __init__(self, card_id, transaction_manager, parent=None):
        """
        初始化月度收支趋势窗口

        参数:
            card_id: 银行卡号
            transaction_manager: 交易管理器实例
            parent: 父窗口
        """
        super().__init__(parent)
        self.card_id = card_id
        self.transaction_manager = TransactionManager()
        self.setup_ui()

    def setup_ui(self):
        """设置界面UI"""
        # 主布局 - 使用垂直布局
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(20, 15, 20, 15)
        main_layout.setSpacing(10)

        # === 标题区域 ===
        title_layout = QHBoxLayout()

        # 主标题
        title_label = QLabel(f"月度收支趋势分析 - 卡号: {self.card_id}")
        title_label.setStyleSheet("""
            font-size: 16px;
            font-weight: bold;
            color: #2c3e50;
        """)
        title_layout.addWidget(title_label)

        # 日期显示
        self.date_label = QLabel(datetime.now().strftime("%Y年%m月"))
        self.date_label.setStyleSheet("font-size: 14px; color: #7f8c8d; font-weight: bold;")
        title_layout.addWidget(self.date_label, 0, Qt.AlignRight)

        main_layout.addLayout(title_layout)

        # 分隔线
        separator = QLabel()
        separator.setFixedHeight(1)
        separator.setStyleSheet("background-color: #e0e0e0;")
        main_layout.addWidget(separator)

        # === 图表区域 ===
        chart_container = QGroupBox("月收入支出趋势图")
        chart_layout = QVBoxLayout(chart_container)

        # 图表视图
        self.chart_view = QChartView()
        self.chart_view.setRenderHint(QPainter.Antialiasing)  # 开启抗锯齿
        self.chart_view.setMinimumHeight(350)
        chart_layout.addWidget(self.chart_view)

        main_layout.addWidget(chart_container)

        # === 控制面板 ===
        control_layout = QHBoxLayout()
        control_layout.setSpacing(15)

        # 年份选择
        control_layout.addWidget(QLabel("年份:"))
        self.year_combo = QComboBox()
        current_year = datetime.now().year
        years = [str(y) for y in range(current_year - 5, current_year + 1)]  # 显示最近5年和当前年
        self.year_combo.addItems(years)
        self.year_combo.setCurrentText(str(current_year))
        self.year_combo.setFixedWidth(100)
        control_layout.addWidget(self.year_combo)

        # 月份选择
        control_layout.addWidget(QLabel("月份:"))
        self.month_combo = QComboBox()
        months = [f"{m:02d}月" for m in range(1, 13)]  # 01月, 02月, ..., 12月
        self.month_combo.addItems(months)
        self.month_combo.setCurrentIndex(datetime.now().month - 1)
        self.month_combo.setFixedWidth(100)
        control_layout.addWidget(self.month_combo)

        # 刷新按钮
        refresh_btn = QPushButton("刷新图表")
        refresh_btn.setStyleSheet("""
            QPushButton {
                background-color: #3498db;
                color: white;
                padding: 8px 16px;
                border-radius: 4px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #2980b9;
            }
        """)
        refresh_btn.setFixedWidth(120)
        refresh_btn.clicked.connect(self.update_chart)
        control_layout.addWidget(refresh_btn)

        control_layout.addStretch(1)
        main_layout.addLayout(control_layout)

        # === 统计信息区域 ===
        stats_layout = QHBoxLayout()
        stats_layout.setSpacing(20)

        # 收入统计
        income_group = QGroupBox("总收入")
        income_group.setStyleSheet("border: 1px solid #27ae60; border-radius: 6px;")
        income_layout = QVBoxLayout(income_group)
        self.income_label = QLabel("¥0.00")
        self.income_label.setStyleSheet("font-size: 18px; color: #27ae60; font-weight: bold;")
        self.income_label.setAlignment(Qt.AlignCenter)
        income_layout.addWidget(self.income_label)
        stats_layout.addWidget(income_group)

        # 支出统计
        expense_group = QGroupBox("总支出")
        expense_group.setStyleSheet("border: 1px solid #e74c3c; border-radius: 6px;")
        expense_layout = QVBoxLayout(expense_group)
        self.expense_label = QLabel("¥0.00")
        self.expense_label.setStyleSheet("font-size: 18px; color: #e74c3c; font-weight: bold;")
        self.expense_label.setAlignment(Qt.AlignCenter)
        expense_layout.addWidget(self.expense_label)
        stats_layout.addWidget(expense_group)

        # 结余统计
        balance_group = QGroupBox("月度结余")
        balance_group.setStyleSheet("border: 1px solid #3498db; border-radius: 6px;")
        balance_layout = QVBoxLayout(balance_group)
        self.balance_label = QLabel("¥0.00")
        self.balance_label.setStyleSheet("font-size: 18px; font-weight: bold;")
        self.balance_label.setAlignment(Qt.AlignCenter)
        balance_layout.addWidget(self.balance_label)
        stats_layout.addWidget(balance_group)

        main_layout.addLayout(stats_layout)

        # 提示信息
        tip_label = QLabel("提示：双击图表可查看详细数据")
        tip_label.setStyleSheet("color: #7f8c8d; font-size: 12px; font-style: italic;")
        tip_label.setAlignment(Qt.AlignRight)
        main_layout.addWidget(tip_label)

        # 初始加载图表
        self.update_chart()

    def update_chart(self):
        """更新图表 - 使用数据库真实交易数据"""
        try:
            # 获取选择的年月
            year = int(self.year_combo.currentText())
            month = self.month_combo.currentIndex() + 1
            self.date_label.setText(f"{year}年{month:02d}月")

            # 从数据库获取指定月份的收支数据
            monthly_data = self.get_monthly_transactions(year, month)

            # 创建图表
            chart = self.create_chart(monthly_data, year, month)

            # 更新图表视图
            self.chart_view.setChart(chart)

            # 更新统计数据
            self.update_statistics(monthly_data)

        except Exception as e:
            print(f"更新图表时出错: {str(e)}")

    def get_monthly_transactions(self, year, month):
        """
        从数据库获取指定月份的收支数据

        返回:
            dict: {
                'daily_data': {1: {'income': 100.0, 'expense': 50.0}, ...},
                'total_income': 3000.0,
                'total_expense': 1500.0
            }
        """
        # 使用 transaction_manager 从数据库获取数据
        daily_data = self.transaction_manager.get_daily_transactions(
            self.card_id, year, month
        )

        total_income = 0
        total_expense = 0

        # 计算月度总收入和总支出
        for day_data in daily_data.values():
            total_income += day_data.get('income', 0)
            total_expense += day_data.get('expense', 0)

        return {
            'daily_data': daily_data,
            'total_income': total_income,
            'total_expense': total_expense
        }

    def create_chart(self, monthly_data, year, month):
        """创建收支趋势图表"""
        chart = QChart()
        chart.setTitle(f"{year}年{month}月收支趋势分析")
        chart.setAnimationOptions(QChart.SeriesAnimations)
        chart.legend().setVisible(True)

        # 创建收入折线（绿色）
        income_series = QLineSeries()
        income_series.setName("收入")
        income_series.setColor(QColor("#27ae60"))

        # 创建支出折线（红色）
        expense_series = QLineSeries()
        expense_series.setName("支出")
        expense_series.setColor(QColor("#e74c3c"))

        # 添加每日数据
        daily_data = monthly_data['daily_data']
        max_value = 0
        days_in_month = len(daily_data)

        for day, data in daily_data.items():
            income = data.get('income', 0)
            expense = data.get('expense', 0)

            income_series.append(day, income)
            expense_series.append(day, expense)

            max_value = max(max_value, income, expense)

        # 添加到图表
        chart.addSeries(income_series)
        chart.addSeries(expense_series)

        # 设置X轴（日期）
        axis_x = QValueAxis()
        axis_x.setTitleText("日期")
        axis_x.setLabelFormat("%d")
        axis_x.setRange(1, days_in_month)
        axis_x.setTickCount(min(days_in_month, 10))  # 合理设置刻度数量

        # 设置Y轴（金额）
        axis_y = QValueAxis()
        axis_y.setTitleText("金额 (元)")
        axis_y.setRange(0, max_value * 1.2)  # Y轴上限为最大值的1.2倍

        # 添加坐标轴
        chart.addAxis(axis_x, Qt.AlignBottom)
        chart.addAxis(axis_y, Qt.AlignLeft)

        # 附加系列到坐标轴
        income_series.attachAxis(axis_x)
        income_series.attachAxis(axis_y)
        expense_series.attachAxis(axis_x)
        expense_series.attachAxis(axis_y)

        return chart

    def update_statistics(self, monthly_data):
        """更新统计信息"""
        total_income = monthly_data['total_income']
        total_expense = monthly_data['total_expense']
        balance = total_income - total_expense

        # 设置收入值
        self.income_label.setText(f"¥{total_income:.2f}")

        # 设置支出值
        self.expense_label.setText(f"¥{total_expense:.2f}")

        # 设置结余值并根据正负设置颜色
        self.balance_label.setText(f"¥{balance:.2f}")
        if balance >= 0:
            self.balance_label.setStyleSheet("font-size: 18px; color: #27ae60; font-weight: bold;")
        else:
            self.balance_label.setStyleSheet("font-size: 18px; color: #e74c3c; font-weight: bold;")

if __name__ == "__main__":
    # 设置日志捕获所有错误
    def global_exception_hook(exctype, value, traceback_obj):
        """全局异常处理钩子"""
        print(f"未捕获的异常: {exctype}, {value}")
        traceback.print_exception(exctype, value, traceback_obj)

        # 创建临时QApplication显示错误
        temp_app = QApplication(sys.argv)
        QMessageBox.critical(None, "未捕获的异常", f"{exctype.__name__}: {value}")
        sys.exit(1)


    sys.excepthook = global_exception_hook

    app = QApplication(sys.argv)

    # 设置全局字体
    font = QFont()
    font.setFamily("Microsoft YaHei" if sys.platform == 'win32' else "Arial")
    font.setPointSize(10)
    app.setFont(font)

    # 显示登录对话框
    login_dialog = CustomerLoginDialog()
    if login_dialog.exec_() == QDialog.Accepted:
        if login_dialog.card_info:
            try:
                customer_dashboard = CustomerDashboard(login_dialog.card_info)
                customer_dashboard.show()
                sys.exit(app.exec_())
            except Exception as e:
                QMessageBox.critical(None, "错误", f"无法创建主界面: {str(e)}")
                sys.exit(1)
        else:
            QMessageBox.critical(None, "错误", "登录失败，未获取卡信息")
            sys.exit(1)
    else:
        sys.exit(0)

